package com.campus.help.controller.admin;

import com.campus.help.common.Result;
import com.campus.help.common.ResultCode;
import com.campus.help.entity.School;
import com.campus.help.service.SchoolService;
import com.campus.help.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 管理员学校管理控制器
 */
@Slf4j
@RestController
@RequestMapping({"/admin/schools", "/admin/school"})
public class AdminSchoolController {

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取学校列表
     */
    @GetMapping
    public Result<List<School>> getSchools(HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            List<School> schools = schoolService.getActiveSchools();
            return Result.success(schools);
        } catch (Exception e) {
            log.error("获取学校列表失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 分页获取学校列表
     */
    @GetMapping("/list")
    public Result<com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.campus.help.vo.SchoolVO>> getSchoolPageList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            log.info("分页获取学校列表 - page: {}, size: {}, status: {}, keyword: {}, province: {}, city: {}",
                    page, size, status, keyword, province, city);

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.campus.help.vo.SchoolVO> schoolPage = 
                    schoolService.getSchoolPageList(page, size, status, keyword, province, city);
            
            return Result.success(schoolPage);
        } catch (Exception e) {
            log.error("获取学校列表失败", e);
            return Result.error("获取学校列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取学校详情
     */
    @GetMapping("/{id}")
    public Result<com.campus.help.vo.SchoolVO> getSchoolById(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            log.info("获取学校详情，ID: {}", id);
            com.campus.help.vo.SchoolVO school = schoolService.getSchoolById(id);
            
            if (school == null) {
                log.warn("学校不存在，ID: {}", id);
                return Result.error("学校不存在");
            }
            
            return Result.success(school);
        } catch (Exception e) {
            log.error("获取学校详情失败，ID: {}", id, e);
            return Result.error("获取学校详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取学校选项列表（用于下拉选择）
     */
    @GetMapping("/options")
    public Result<List<School>> getSchoolOptions(HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            List<School> schools = schoolService.getActiveSchools();
            return Result.success(schools);
        } catch (Exception e) {
            log.error("获取学校选项列表失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 添加学校
     */
    @PostMapping
    public Result<String> addSchool(@RequestBody School school, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            log.info("添加学校请求: name={}, code={}, address={}", 
                    school.getName(), school.getCode(), school.getAddress());

            // 参数校验
            if (school.getName() == null || school.getName().trim().isEmpty()) {
                return Result.error("学校名称不能为空");
            }

            boolean success = schoolService.addSchool(school);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加学校失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新学校信息
     */
    @PutMapping("/{id}")
    public Result<String> updateSchool(
            @PathVariable Long id,
            @RequestBody School school,
            HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            log.info("更新学校请求: id={}, name={}, code={}, address={}", 
                    id, school.getName(), school.getCode(), school.getAddress());

            // 参数校验
            if (school.getName() == null || school.getName().trim().isEmpty()) {
                return Result.error("学校名称不能为空");
            }

            // 设置ID
            school.setId(id);

            boolean success = schoolService.updateSchool(school);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新学校失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除学校
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteSchool(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            log.info("删除学校请求: id={}", id);

            boolean success = schoolService.deleteSchool(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除学校失败: id={}", id, e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除学校
     */
    @PostMapping("/batch-delete")
    public Result<String> batchDeleteSchools(
            @RequestBody List<Long> ids,
            HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            log.info("批量删除学校请求: ids={}", ids);

            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的学校");
            }

            boolean success = schoolService.batchDeleteSchools(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除学校失败: ids={}", ids, e);
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 更新学校状态
     */
    @PutMapping("/{id}/status")
    public Result<String> updateSchoolStatus(
            @PathVariable Long id,
            @RequestParam String status,
            HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            log.info("更新学校状态请求: id={}, status={}", id, status);

            boolean success = schoolService.updateSchoolStatus(id, status);
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新学校状态失败: id={}, status={}", id, status, e);
            return Result.error("状态更新失败: " + e.getMessage());
        }
    }

    /**
     * 验证管理员token
     */
    private boolean validateAdminToken(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return false;
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            return tokenInfo != null && "admin".equals(tokenInfo.getType());
        } catch (Exception e) {
            log.error("验证管理员token失败", e);
            return false;
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
}
